import { useEffect, useRef, useState } from 'react';
import { DeleteOutlined, PlusOutlined, EditOutlined } from '@ant-design/icons';
import {
  PageContainer,
  ProTable,
  ModalForm,
  ProFormText,
  ProForm,
  ProFormTextArea,
  ProFormDigit,
} from '@ant-design/pro-components';
import { Button, Space, Popconfirm } from 'antd';
import {
  loadDataAPI,
  addOneAPI,
  modifyByIdAPI,
  loadOneByIdAPI,
  deleteByIdAPI,
  deleteManyByIds,
} from '@/services/yaopin.ts';
import { dalImg } from '@/utils/tools';
import MyUpload from '../../components/myupload/MyUpload';
import MyEditor from '../../components/myupload/MyEditor';

function Yplb() {
  const [isShow, setIsShow] = useState(false);
  const actionRef = useRef();
  const [currentId, setCurrentID] = useState(''); //记录当前Id，区分时修改还是新增
  const [myForm] = ProForm.useForm(); //获取表单
  const [selRows, setSelRows] = useState([]); //选中行id
  const [imageUrl, setImageUrl] = useState('');
  const [html, setHtml] = useState('');

  //关闭窗口之后，重置数据
  useEffect(() => {
    if (!isShow) {
      setCurrentID('');
      setImageUrl('');
      setHtml('');
    }
  }, [isShow]);

  //当前的数据列
  const columns = [
    {
      title: '序号',
      align: 'center',
      hideInSearch: true,
      render(c, r, i) {
        return i + 1;
      },
    },
    {
      title: '药品名称',
      align: 'center',

      dataIndex: 'name',
    },
    {
      title: '药品图片',
      align: 'center',
      hideInSearch: true,
      render(v) {
        return <img src={dalImg(v.image)} className="ypimg" />;
      },
    },
    {
      title: '药品简介',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'desc',
    },
    {
      title: '价格',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'price',
    },
    {
      title: '数量',
      align: 'center',
      hideInSearch: true,
      dataIndex: 'amount',
    },
    {
      title: '药品操作',
      hideInSearch: true,
      render(v) {
        return (
          <Space>
            <Button
              type="primary"
              icon={<EditOutlined />}
              size="small"
              onClick={async () => {
                //要先获取数据
                // id应该等于当前的id
                const info = await loadOneByIdAPI(v.id);
                // console.log(info);
                myForm.setFieldsValue(info.data);
                setImageUrl(info.data.image);
                setHtml(info.data.content);
                setIsShow(true);
                setCurrentID(v.id);
              }}
            />
            {/* 删除按钮,调接口删除，删除完重置数据 */}
            <Popconfirm
              title="是否确认删除？"
              onConfirm={async () => {
                await deleteByIdAPI(v.id);
                actionRef.current?.reload();
              }}
            >
              <Button type="primary" danger icon={<DeleteOutlined />} size="small" />
            </Popconfirm>
          </Space>
        );
      },
    },
  ];

  return (
    <PageContainer>
      <ProTable
        // 多选
        rowKey="id"
        rowSelection={{
          selectedRowKeys: selRows, //设置当前选中的
          onChange(selectedRowKeys) {
            //  console.log(selectedRowKeys);
            //把选中的值设置给变量
            setSelRows(selectedRowKeys);
          },
        }}
        // 这个属性可以直接操作表格中的各种方法
        actionRef={actionRef}
        columns={columns}
        request={loadDataAPI}
        // dataSource={
        //   data
        // }
        toolBarRender={() => {
          //操作按钮数据，默认只有一个新增按钮
          const tools = [
            <Button
              type="primary"
              icon={<PlusOutlined />}
              key="primary"
              onClick={() => {
                setIsShow(true);
              }}
            />,
          ];
          // 如果勾选了指定的行，显示多行删除按钮
          if (selRows.length > 0) {
            // 如果有数据就push一个按钮
            tools.push(
              <Button
                type="primary"
                danger
                key={2}
                onClick={async () => {
                  //通过join拼接数组
                  await deleteManyByIds(selRows.join(','));
                  actionRef.current?.reload(); //删除后重新加载
                  setSelRows([]); //清空选中的值
                }}
              >
                批量删除
              </Button>,
            );
          }
          return tools;
        }}
      />
      <ModalForm
        form={myForm}
        title="编辑"
        open={isShow}
        // 模态框的属性，点击遮罩层模态框不消失
        modalProps={{
          maskClosable: false,
          destroyOnClose: true,
        }}
        //open状态改变
        onOpenChange={setIsShow}
        //提交的时候执行
        onFinish={async (v) => {
          // console.log(v);
          //调接口存储数据,存在的话修改，不存在新增
          if (currentId) {
            await modifyByIdAPI(currentId, { ...v, image: imageUrl, content: html });
          } else {
            await addOneAPI({ ...v, image: imageUrl, content: html });
          }

          setIsShow(false);
          actionRef.current?.reload();
          // actionRef.current可以获取ProTable,接受一个reload方法，reload之后可以重新加载数据
          //重新加载数据
        }}
      >
        <ProFormText
          label="药品名字"
          placeholder="请输入药品名字"
          //加name才能生效
          name="name"
          rules={[
            {
              required: true,
              message: '药品名字不能为空',
            },
          ]}
        />
        <ProFormTextArea placeholder="请输入药品简介" name="desc" />
        <ProFormDigit label="价格" name="price"></ProFormDigit>
        <ProFormDigit label="数量" name="amount"></ProFormDigit>
        <ProForm.Item label="主图">
          <MyUpload imageUrl={imageUrl} setImageUrl={setImageUrl} />
        </ProForm.Item>

        <ProForm.Item label="详情">
          <MyEditor html={html} setHtml={setHtml} />
        </ProForm.Item>
      </ModalForm>
    </PageContainer>
  );
}

export default Yplb;
